package bt.basics.common.handler;

import bt.basics.modules.security.user.SecurityUser;
import bt.basics.modules.security.user.UserDetail;
import bt.basics.modules.sys.entity.SysUserEntity;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 公共字段，自动填充值
 *
 *
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_DATE = "createDate";
    private final static String CREATOR = "creator";
    private final static String CREATEBY = "createby";
    private final static String UPDATE_DATE = "updateDate";
    private final static String UPDATER = "updater";
    private final static String UPDATEBY = "updateby";
    private final static String DEPT_ID = "deptId";

    @Override
    public void insertFill(MetaObject metaObject) {
        SysUserEntity entity = null;
        try {
            entity = (SysUserEntity)metaObject.getOriginalObject();
        }catch (Exception e){

        }

        UserDetail user = SecurityUser.getUser();
        Date date = new Date();

        //创建者
        setFieldValByName(CREATOR, user.getId(), metaObject);
        //创建时间
        setFieldValByName(CREATE_DATE, date, metaObject);
        //创建人姓名
        setFieldValByName(CREATEBY, user.getRealName(), metaObject);

        //更新者
        setFieldValByName(UPDATER, user.getId(), metaObject);
        //更新时间
        setFieldValByName(UPDATE_DATE, date, metaObject);
        //更新人姓名
        setFieldValByName(UPDATEBY, user.getRealName(), metaObject);
        //创建者所属部门
        setFieldValByName(DEPT_ID, user.getDeptId(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新者
        setFieldValByName(UPDATER, SecurityUser.getUserId(), metaObject);
        //更新时间
        setFieldValByName(UPDATE_DATE, new Date(), metaObject);
        //更新人姓名
        setFieldValByName(UPDATEBY, SecurityUser.getUser().getRealName(), metaObject);
    }
}